﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Text;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Interop;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;
using Fluent;
using OccExample.Commands;
using OccExample.Commands.Tests;
using Tx.OCC.UI;
using Tx.OCC.UI.WPF;
using Tx;
using Tx.FluentEx;
using Tx.Win;
using Tx.WPF;

namespace OccExample
{
    /// <summary>
    /// Interaction logic for MainWindow.xaml
    /// </summary>
    public partial class MainWindow : RibbonWindow, IMainWindow, IViewWindow, INotifyPropertyChanged
    {
        public event PropertyChangedEventHandler PropertyChanged;
        protected void RaisePropertyChanged(string thePropertyName)
        {
            PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(thePropertyName));
        }
        public AppService App { get; private set; }

        private void InitAppService()
        {
            App = new AppService() { MainWindow = this };
            // 绑定预定义的消息
            App.SingletonSet(MessageBoxEx.MessageProxy);
            App.Singleton<ProgressProxy>().OnSetText += (sender, args) =>
            {
                this.SafeInvoke(() =>
                {
                    if (args.Caption != null && tbInfo.Text != args.Caption)
                    {
                        tbInfo.Text = args.Caption;
                    }
                });
            };
            App.Singleton<ProgressProxy>().OnSetValue += (sender, args) =>
            {
                this.SafeInvoke(() =>
                {
                    //                     bool bRefresh = false;
                    //                     if (value > 0 && tsProgressBar.Value != value)
                    //                     {
                    TaskbarManager.Instance.SetProgressValue(args.Value, 100, this.Handle);
                    // 
                    //                         tsProgressBar.Value = value;
                    //                         bRefresh = true;
                    //                     }
                    // 
                    //                     if (bRefresh)
                    //                     {
                    //                         statusStrip.Refresh();
                    //                         Application.DoEvents();
                    //                     }
                });
            };
            App.Singleton<ProgressProxy>().OnClear += (sender, args) =>
            {
                this.SafeInvoke(() =>
                {
                    TaskbarManager.Instance.SetProgressValue(0, 100, this.Handle);

                    //tbInfo.Text = "就绪";
                    //tsProgressBar.Value = 0;
                    //statusStrip.Refresh();
                    //Application.DoEvents();
                });
            };
        }

        #region IWindow

        public new string Title
        {
            get => base.Title;
            set => base.Title = value;
        }

        /// <summary>Window句柄.</summary>
        /// <value>The handle.</value>
        public IntPtr Handle => ((HwndSource)PresentationSource.FromDependencyObject(this)).Handle;

        /// <summary>图标.</summary>
        /// <value>The icon.</value>
        public object IconImage
        {
            get
            {
                return this.Icon;
            }
            set
            {
                this.Icon = value as ImageSource;
            }
        }

        #endregion

        #region IMainWindow

        /// <summary>Gets the active view window.</summary>
        /// <value>The active view window.</value>
        public object ActiveViewWindow => this;

        /// <summary>更新UI.</summary>
        public void RefreshUI()
        {
            this.InvalidateVisual();
        }

        /// <summary>Occurs when [view window active].</summary>
        public event Action<IViewWindow> ViewWindowActive;

        #endregion

        #region IViewWindow

        /// <summary>
        /// Gets the parent.
        /// </summary>
        /// <value>The parent.</value>
        public object ParentWindow => this.Owner;

        /// <summary>
        /// Gets the view.
        /// </summary>
        /// <value>The view.</value>
        public object View => ActiveViewer;

        #endregion


        public MainWindow()
        {
            InitializeComponent();
            InitAppService();
            InitRibbon();
        }

        private void InitRibbon()
        {
            var ribbonCreater = new RibbonBuilder(ribbon, App);
            ribbonCreater.Tab("文件").Group("文件")
                .AddBotton<DocNewCmd>("新建", "/Resources/0_48px.png")
                .AddBotton<DocCloseCmd>("关闭", "/Resources/1_48px.png");
            ribbonCreater.Tab("测试").Group("测试")
                .AddBotton<TextLabelTestCmd>("文字测试", "/Resources/0_48px.png");
            //             ribbonCreater.Tab("地球").Group("图层")
            //                 //.AddBotton<HideOrShowTiandituCiaCmd>("天地图矢量", "/Resources/maps.png")
            //                 .AddBotton(Cmds.AddImageLayer, "添加影像", "/Resources/maps.png")
            //                 .AddBotton(Cmds.AddElevationLayer, "添加高程", "/Resources/maps.png");
            //             ribbonCreater.Tab("测试").Group("渲染")
            //                 .AddBotton<AddStatsHandlerCmd>("渲染信息", "/Resources/0_48px.png")
            //                 .AddBotton<AddStateSetManipulatorCmd>("渲染模式", "/Resources/1_48px.png");
        }


        private OcctView ActiveViewer
        {
            get
            {
                if (!IsDocumentOpen)
                    return null;
                return ViewPanel.SelectedContent as OcctView;
            }
        }

        public Boolean IsDocumentOpen => ViewPanel.Items.Count > 0;

        [System.Runtime.InteropServices.DllImport("user32.dll", EntryPoint = "SetParent")]
        private extern static IntPtr SetParent(IntPtr childPtr, IntPtr parentPtr);

        private void QuitCommand_Executed(object sender, ExecutedRoutedEventArgs e)
        {
            this.Close();
        }


        private int myDocumentCounter = 1;

        public void DocNew()
        {
            TabItem aNewTab = new TabItem();
            aNewTab.Content = new OcctView();

            aNewTab.HorizontalAlignment = System.Windows.HorizontalAlignment.Stretch;
            aNewTab.HorizontalContentAlignment = System.Windows.HorizontalAlignment.Stretch;
            aNewTab.VerticalContentAlignment = System.Windows.VerticalAlignment.Stretch;


            aNewTab.IsSelected = true;
            aNewTab.Header = "Document " + myDocumentCounter.ToString();
            myDocumentCounter++;

            ViewPanel.Items.Add(aNewTab);

            ViewPanel.Focus();

            // update XAML property
            RaisePropertyChanged("IsDocumentOpen");
        }

        public void DocClose()
        {
            if (ViewPanel.Items.Count > 0)
            {
                var activeViewer = ActiveViewer;
                ViewPanel.Items.Remove(ViewPanel.SelectedItem);
                try
                {
                    activeViewer.Dispose();
                }
                catch (Exception exception)
                {
                }
            }

            // update XAML property
            RaisePropertyChanged("IsDocumentOpen");
        }

        public bool IsWireframeEnabled
        {
            get
            {
                if (ActiveViewer != null)
                {
                    return ActiveViewer.Viwer.Viewer.IsWireframeEnabled;
                }
                return false;
            }
        }

        private void Wireframe_Click(object sender, RoutedEventArgs e)
        {
            if (ActiveViewer != null)
            {
                ActiveViewer.Viwer.Viewer.Wireframe();
            }
        }

        private void Shading_Click(object sender, RoutedEventArgs e)
        {
            if (ActiveViewer != null)
            {
                ActiveViewer.Viwer.Viewer.Shading();
            }
        }

        public bool IsShadingEnabled
        {
            get
            {
                if (ActiveViewer != null)
                {
                    return ActiveViewer.Viwer.Viewer.IsShadingEnabled;
                }
                return false;
            }
        }

        private void Color_Click(object sender, RoutedEventArgs e)
        {
            if (ActiveViewer != null)
            {
                ActiveViewer.Viwer.Viewer.Color();
            }
        }

        public bool IsColorEnabled
        {
            get
            {
                if (ActiveViewer != null)
                {
                    return ActiveViewer.Viwer.Viewer.IsColorEnabled;
                }
                return false;
            }
        }

        private void Material_Click(object sender, RoutedEventArgs e)
        {
            if (ActiveViewer != null)
            {
                ActiveViewer.Viwer.Viewer.Material();
            }
        }

        public bool IsMaterialEnabled
        {
            get
            {
                if (ActiveViewer != null)
                {
                    return ActiveViewer.Viwer.Viewer.IsMaterialEnabled;
                }
                return false;
            }
        }

        private void Transparency_Click(object sender, RoutedEventArgs e)
        {
            if (ActiveViewer != null)
            {
                ActiveViewer.Viwer.Viewer.Transparency();
            }
        }

        public bool IsTransparencyEnabled
        {
            get
            {
                if (ActiveViewer != null)
                {
                    return ActiveViewer.Viwer.Viewer.IsTransparencyEnabled;
                }
                return false;
            }
        }

        private void Delete_Click(object sender, RoutedEventArgs e)
        {
            if (ActiveViewer != null)
            {
                ActiveViewer.Viwer.Viewer.Delete();
            }
        }

        private void Background_Click(object sender, RoutedEventArgs e)
        {
            if (ActiveViewer != null)
            {
                ActiveViewer.Viwer.Viewer.Background();
            }
        }

        public bool IsDeleteEnabled
        {
            get
            {
                if (ActiveViewer != null)
                {
                    return ActiveViewer.Viwer.Viewer.IsDeleteEnabled;
                }
                return false;
            }
        }

        private void AvaliabiltyOfOperationToolbarChanged()
        {
            RaisePropertyChanged("IsWireframeEnabled");
            RaisePropertyChanged("IsShadingEnabled");
            RaisePropertyChanged("IsTransparencyEnabled");
            RaisePropertyChanged("IsColorEnabled");
            RaisePropertyChanged("IsMaterialEnabled");
            RaisePropertyChanged("IsDeleteEnabled");
        }

        public void OnAvaliabiltyOfOperationsChanged(object sender, EventArgs e)
        {
            AvaliabiltyOfOperationToolbarChanged();
        }

        private void OnViewerChanged(object sender, SelectionChangedEventArgs e)
        {
            if (e.RemovedItems.Count > 0)
            {
                OcctView aHost = ((e.RemovedItems[0] as TabItem).Content) as OcctView;
                if (aHost == null)
                {
                    return;
                }

                if (ActiveViewer != null)
                {
                    //ActiveViewer.Viewer.ZoomingFinished -= new EventHandler(OnZoomingFinished);
                    ActiveViewer.Viwer.Viewer.AvaliabiltyOfOperationsChanged -= new EventHandler(OnAvaliabiltyOfOperationsChanged);
                }
            }

            if (e.AddedItems.Count > 0)
            {
                OcctView aHost = ((e.AddedItems[0] as TabItem).Content) as OcctView;
                if (aHost == null)
                {
                    return;
                }

                if (ActiveViewer != null)
                {
                    //ActiveViewer.Viewer.ZoomingFinished += new EventHandler(OnZoomingFinished);
                    ActiveViewer.Viwer.Viewer.AvaliabiltyOfOperationsChanged += new EventHandler(OnAvaliabiltyOfOperationsChanged);
                }
            }

            AvaliabiltyOfOperationToolbarChanged();
        }

        private void OnContextOpened(object sender, RoutedEventArgs e)
        {
            this.WireframeItem.IsEnabled = IsWireframeEnabled;
            this.ShadingItem.IsEnabled = IsShadingEnabled;
            this.ColorItem.IsEnabled = IsColorEnabled;
            this.MaterialItem.IsEnabled = IsMaterialEnabled;
            this.TransparencyItem.IsEnabled = IsTransparencyEnabled;
            this.DeleteItem.IsEnabled = IsDeleteEnabled;
        }
    }
}